<template>
  <div class="websocket">
     <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="活动名称">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">立即发送</el-button>
                <el-button>取消</el-button>
            </el-form-item>
      </el-form>

      <div class="">
          <h1>接收到的消息:</h1>
            <p v-for="(i,index) in receiveMsg" :key="index">{{i}}</p>

      </div>
  </div>
</template>
<script>
  export default{
    data(){
       return{
            socket:{},//socket创建实例对象
            path:'ws://121.40.165.18:8800',
            // path:'ws://192.168.1.38:5155/ws',//需要连接的地址
            form:{
                name:''
            },
            receiveMsg:[],
       }
    },
    mounted(){
this.init()
    },
    methods:{
        init(){
                if(typeof(WebSocket) === "undefined"){
                    alert("您的浏览器不支持socket")
                }else{
                    // 实例化socket
                    this.socket = new WebSocket(this.path)
                    this.socket.onopen = this.open
                    
                    // 监听socket错误信息
                    this.socket.onerror = this.error
                    // 监听socket消息
                    this.socket.onmessage = this.getMessage
                }
            },
            open(){
                console.log("连接成功")
               
            },
            error(){
                 console.log("连接错误")
            },
            getMessage(res){
                console.log("收取到的信息",res)
                this.receiveMsg.push(res.data)
            },
            //发送信息
            onSubmit(){
                console.log(this.form.name)
                if(this.socket.readyState===1){
                  console.log('已经链接并且可以通讯')
                this.socket.send(this.form.name)
                      
                }
                if(this.socket.readyState===0){
                  console.log('正在链接中')
                }
                if(this.socket.readyState===2){
                  console.log('连接正在关闭')
                }
                if(this.socket.readyState===3){
                  console.log('连接已关闭或者没有链接成功')
                }
            },
    }
  }
</script>
<style>
      .websocket{
        width: 100%;
        height: 100%;
        background: white;
    }
</style>
